package com.wskj.ws.interceptor;

import org.springframework.http.server.ServerHttpRequest;
import org.springframework.http.server.ServerHttpResponse;
import org.springframework.web.socket.WebSocketHandler;
import org.springframework.web.socket.server.HandshakeInterceptor;

import java.util.Map;

/**
 * 创建拦截器 MyWebSocketInterceptor
 */
public class MyWebSocketInterceptor implements HandshakeInterceptor {
    @Override
    public boolean beforeHandshake(ServerHttpRequest servletRequest, ServerHttpResponse servletResponse, WebSocketHandler wsHandler, Map<String, Object> attributes) throws Exception {
        System.out.println("websocket前置拦截");

        //如果用到Sec-WebSocket-Protocol，可以采用getHeaders().get(key)的方法获取
        /*if (servletRequest.getHeaders().get("Sec-WebSocket-Protocol") == null) {
            System.out.println("无Sec-WebSocket-Protocol，进行拦截！");
            return false;
        }
        String protocol = servletRequest.getHeaders().get("Sec-WebSocket-Protocol").get(0);*/

        //如果uri的路径中带有参数，可获取到uri字符串，采用截取的方式处理，最后存入attributes
        String path = servletRequest.getURI().getPath();
        if(path.lastIndexOf('/')>0) {
            String id = path.substring(path.lastIndexOf('/') + 1);
            attributes.put("identifier", id);
        }
        return true;
    }

    @Override
    public void afterHandshake(ServerHttpRequest request, ServerHttpResponse response, WebSocketHandler wsHandler, Exception exception) {
        System.out.println("websocket后置拦截");
    }
}
